﻿using ESRI.ArcGIS.Client;
using ESRI.ArcGIS.Client.Geometry;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DGIS.Map.Layers
{
    public class BingImgLayer : TiledMapServiceLayer
    {
        public override void Initialize()
        {
            this.SpatialReference = new SpatialReference(3857);

            this.FullExtent = new Envelope(-16777216, -16777216, 16777216, 16777216);
            {
                SpatialReference = this.SpatialReference;
            };


            this.TileInfo = new TileInfo()
            {
                Height = 256,
                Width = 256,

                Origin = new MapPoint(-20037588.34278925, 20037518.34278925)
                {
                    SpatialReference = this.SpatialReference
                },
                Lods = new Lod[17]
            };

            double resolution = 156543.033928;
            for (int i = 0; i < TileInfo.Lods.Length; i++)
            {
                TileInfo.Lods[i] = new Lod()
                {
                    Resolution = resolution
                };
                resolution /= 2;
            }

            base.Initialize();
        }

        public override string GetTileUrl(int level, int row, int col)
        {
            var s = (level + row + col) % 3;
            var r = TileXYToQuadKey(col, row, level);
            //return "http://ecn.t" + s + ".tiles.virtualearth.net/tiles/a" + r + ".jpeg?g=915&mkt=en-us&n=z&token=22";
            return "http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/" + level + "/" + row + "/" + col;
        }
        
        private string TileXYToQuadKey(int x, int y, int l)
        {
            var key = "";
            for (var i = l; i > 0; i--)
            {
                var digit = '0';
                var mask = 1 << (i - 1);//掩码，最高位设为1，其他位设为0
                if ((x & mask) != 0)//与运算取得tileX的最高位，若为1，则加1
                {
                    digit++;
                }
                if ((y & mask) != 0)//与运算取得tileY的最高位，若为1，则加2
                {
                    digit++;
                    digit++;
                }
                key += digit;//也即2*y+x
            }
            return key;
        }
    }
}
